#include "SessionHandler.h"
#include "TCPChannel.h"
#include "util.h"
#include <unistd.h>

namespace qy
{

SessionHandler::SessionHandler(int sock, void (*callback)(SessionHandler*))
:m_callback(callback)
{
	m_channel = new TCPChannel(sock); 
}

SessionHandler::~SessionHandler()
{
	delete_null(m_channel);
}

int SessionHandler::run()
{
	const int MaxSeconds = 60;
	int seconds = 2;
	while(seconds < MaxSeconds)
	{
		if(m_channel->canReceive())
		{
			char buf[1025];
			int len = m_channel->receive(buf, 1024);
			if(len > 0)
			{
				buf[len] = '\0';
				log_debug("Receive: %s", buf);
				seconds = 0;
			}
			else
			{
				log_debug("Connection Closed");
				break;
			}
			if(m_channel->canSend())
			{
				m_channel->send("hello", 5);
				seconds = 0;
			}
		}
		sleep(seconds);
		seconds += 2;
	}
	return 0;
}

void SessionHandler::afterRun()
{
	delete_null(m_channel);
	if(m_callback)
	{
		m_callback(this);
	}
}

}
